package com.copm.ifm.servers.sys.file.obs;

import com.copm.ifm.base.basic.exception.ServiceException;
import com.copm.ifm.servers.sys.entity.SysFile;
import com.copm.ifm.servers.sys.file.FileClient;
import com.copm.ifm.servers.sys.file.FileClientEnum;
import com.obs.services.ObsClient;
import com.obs.services.model.DeleteObjectResult;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 华为OBS文件系统
 *
 * @author zzf
 * @date 2021/4/28 14:15
 */
public class ObsFileClient implements FileClient {

    private final ObsClient obsClient;

    public ObsFileClient(String endPoint, String appKey, String secretKey) {
        obsClient = new ObsClient(appKey, secretKey, endPoint);
    }

    /**
     * 文件上传
     *
     * @param path     存储路径
     * @param fileName 文件名
     * @param file     文件对象
     * @return 文件访问url
     */
    @Override
    public String uploadFile(String path, String fileName, MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            PutObjectResult putObjectResult = obsClient.putObject(path, fileName, inputStream);
            return putObjectResult.getObjectUrl();
        } catch (IOException e) {
            throw new ServiceException("文件上传失败！", e);
        }
    }

    /**
     * 文件下载
     *
     * @param sysFile 文件
     */
    @Override
    public void downLoadFile(SysFile sysFile) throws IOException {
        ObsObject obsObject = obsClient.getObject(sysFile.getBucket(), sysFile.getObjectKey());
        // 读取对象内容
        InputStream input = obsObject.getObjectContent();
        byte[] b = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len;
        while ((len = input.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        //暂时做打印处理，联调更改为跟前端交互
        System.out.println(bos.toString());
    }

    /**
     * 删除文件
     *
     * @param path     存储路径
     * @param fileName 文件名
     * @return 是否成功
     */
    @Override
    public boolean deleteFile(String path, String fileName) {
        DeleteObjectResult deleteObjectResult = obsClient.deleteObject(path, fileName);
        return deleteObjectResult.isDeleteMarker();
    }

    /**
     * 客户端唯一标识
     *
     * @return
     */
    @Override
    public FileClientEnum getId() {
        return FileClientEnum.OBS;
    }
}
